<template>
  <div style="padding: 15px;">
    <el-form ref="form" :rules="rules" :model="form" label-width="80px">
      <el-row>
        <el-col :span="8">
          <div class="grid-content bg-purple">
            <el-form-item  label="入驻商" style="margin-right:15px" prop="shipmentCode" >
              <shipmentSelect ref="shipmentSelect" url="/wms/warehouseShipment/business/shipments"  @setCustomerCode="setCustomerCode" style="width: 100%"/>
            </el-form-item>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="grid-content bg-purple">
            <el-form-item label="调出仓库" style="margin-right:15px"  prop="sourceWarehouseCode">
              <el-select v-model="form.sourceWarehouseCode"  placeholder="请选择仓库" style="width:100%" clearable>
                <el-option
                  v-for="item in warehouseData"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code"
                />
              </el-select>
            </el-form-item>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="grid-content bg-purple">
            <el-form-item label="调入仓库" style="margin-right:15px"  prop="targetWarehouseCode">
              <el-select v-model="form.targetWarehouseCode"  placeholder="请选择仓库" style="width:100%" clearable>
                <el-option
                  v-for="item in targetWarehouseData"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code"
                />
              </el-select>
            </el-form-item>
          </div>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <div class="grid-content bg-purple">
            <el-form-item style="margin-right:15px" label="备注">
              <el-input v-model="form.remarks" style="width:100%"  />
            </el-form-item>
          </div>
        </el-col>
      </el-row>
    </el-form>
    <vxe-table
      border
      keep-source
      resizable
      show-overflow
      ref="xTable"
      :align="allAlign"
      :data="tableData"
      show-footer
      :footer-method="footerMethod"
      :edit-rules="validRules"
      :edit-config="{trigger: 'click', mode: 'cell'}">
      <vxe-table-column type="seq" width="60"></vxe-table-column>
      <vxe-table-column field="goodsName" title="商品名称" :edit-render="{name: 'ElSelect'}" width="270">
        <template v-slot:edit="{ row }">
          <goodsSelect  :val2="form.shipmentCode" ref="goodsSelect"  @setGoodsCode="setGoodsCode(row)" />
        </template>
      </vxe-table-column>
      <vxe-table-column field="goodCode" title="商品编码"  width="120"></vxe-table-column>
      <vxe-table-column field="goodsBarCode" title="商品条码"  width="120"></vxe-table-column>
      <vxe-table-column field="allocationUnitName" title="单位"  :edit-render="{}" width="270">
        <template v-slot:edit="{ row }">
          <el-select v-model="row.allocationUnitName" placeholder="请输入单位" style="width:100%" @change="nameChangeEvent(row)" >
            <el-option
              v-for="item in row.goodsUnitConversionList"
              :key="item.unitName"
              :label="item.unitName"
              :value="item.unitName"
            />
          </el-select>
        </template>
      </vxe-table-column>
      <vxe-table-column field="allocationUnitQuantity" title="调拨数量" :edit-render="{name: 'input'}" width="120"></vxe-table-column>
      <vxe-table-column field="remarks" title="备注" :edit-render="{name: 'input'}" width="270"></vxe-table-column>
      <vxe-table-column title="操作"  fixed="right" min-width="100">

        <template v-slot:default="{ row, rowIndex }">
          <vxe-button type="text" @click="insertEvent(rowIndex)">
            <i class="el-icon-plus" />
          </vxe-button>
          <vxe-button type="text" @click="delRowEvent(row,rowIndex)" v-if="row.isShow">
            <i class="el-icon-minus" />
          </vxe-button>
        </template>
      </vxe-table-column>
    </vxe-table>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="funcSubmitSave" :disabled="isDisable" plain>保 存</el-button>
      <el-button type="primary" @click="funcSubmitCheck" :disabled="isDisable" plain>提 交</el-button>
    </div>
  </div>
</template>
<script>
  import request from '@/utils/request'
  import Vue from 'vue'
  import 'xe-utils'
  import VXETable from 'vxe-table'
  import 'vxe-table/lib/index.css'
  import XEUtils from 'xe-utils'
  import VXEUtils from 'vxe-utils'
  import VXETablePluginElement from 'vxe-table-plugin-element'
  import 'vxe-table-plugin-element/dist/style.css'
  import goodsSelect from '@/views/components/goodsElSelect.vue'
  import { allocationAdd, targetWarehouses} from '@/api/store'
  import shipmentSelect from '@/views/components/shipmentSelect.vue'
  import warehouseSelect from '@/views/components/warehouseSelect.vue'


  Vue.use(VXETable, VXEUtils, XEUtils, { mounts: ['cookie'] })
  VXETable.use(VXETablePluginElement)
  export default {
    name: 'Parent',
    components: {
      goodsSelect,
      warehouseSelect,
      shipmentSelect,
    },
    data() {
      return {
        totalRowNum: 0,
        allAlign:'center',
        warehouseData:[],
        targetWarehouseData:[],
        shipmentData:[],
        typeList: [],
        isDisable:false,   //确定键显示按钮
        typeList: [],
        form: {
          shipmentCode: '',
          type:'',
          warehouseCode:"",
          supplierCode:'',
          sourceWarehouseCode:'',
          targetWarehouseCode:'',
          remarks: '', // 备注
          allocationItemList: [],
          // collectBy: '',
          // collectName: '',
          // collectDept: '',
        },
        loading: false,
        tableData: [{}],
        rules: {
          shipmentCode: [
            { required: true, message: '请选择入驻商', trigger: 'change' }
          ],
          sourceWarehouseCode: [
            { required: true, message: '请选择仓库', trigger: 'change' }
          ],
          targetWarehouseCode: [
            { required: true, message: '请选择仓库', trigger: 'change' }
          ],

          type: [
            { required: true, message: '请选择领用类型', trigger: 'change' }
          ]
        },
        validRules: {
          goodsName: [
            { required: true, message: '商品名称必须填写' },
          ],
          allocationUnitName: [
            { required: true, message: '单位必须填写' },
          ],
          allocationUnitQuantity: [
            { required: true, message: '数量必须填写' },
            { pattern: /^(?!(0[0-9]{0,}$))[0-9]{1,}[.]{0,}[0-9]{0,}$/, message: '数量必须大于0' },
            { max: 10, message: '数量不能超过10位'}
          ]
        }
      }
    },
    created() {
    },
    methods: {
      findWarehousetData(shipmentCode) {
        return request({
          url: '/wms/warehouse/business/warehouse',
          method: 'get',
          params: { shipmentCode: shipmentCode }
        }).then(response => {
          this.warehouseData = response.data
          if(this.warehouseData.length === 1){
            this.form.sourceWarehouseCode = this.warehouseData[0].code
          }
        })
      },
      // 获取 调拨单新增 - 调入仓库 下拉框数据
      getTargetWarehouses(shipmentCode) {
        return targetWarehouses(shipmentCode).then((response) => {
          this.targetWarehouseData = response.data;
        });
      },
      // 选择入驻商
      setCustomerCode(e) {
        this.form.shipmentCode = e;
        this.tableData = [{}];
        this.form.targetWarehouseCode = '';
        this.form.sourceWarehouseCode = '';
        this.findWarehousetData(e)
        this.getTargetWarehouses(e)
      },
    insertEvent(rowIndex) {
      const record = {
        isShow:'true'

      }
      this.tableData.splice(rowIndex + 1, 0, record)
    },
    delRowEvent(row, rowIndex) {
      this.$confirm('确认刪除吗？')
        .then(_ => {
          this.tableData.splice(rowIndex, 1)
        })
        .catch(_ => {})
    },
    //计算基本单位
    nameChangeEvent (row) {
      const sd = row.goodsUnitConversionList.find(i => i.unitName == row.allocationUnitName)
      row.allocationUnit = sd.unitCode
      row.unitConvertQuantity = sd.quantity

      row.allocationUnitName = sd.unitName
    },

      //商品选择
      setGoodsCode(row){
        let obj = this.$refs.goodsSelect.obj
        row.goodsName = obj.name
        row.goodsCode = obj.code
        row.goodCode = obj.goodCode
        row.unitName = obj.unitName
        row.unitCode = obj.unitCode
        row.goodsBarCode = obj.barCode
        row.basicUnit = obj.unitCode
        row.basicUnitName = obj.basicUnitName
        row.spec = obj.spec
        row.expirationQuantity = obj.quality
        row.goodsUnitConversionList = obj.goodsUnitConversionList
        // 清空单位
        if (row.goodsUnitConversionList.length === 1) {
          row.unitConvertQuantity = row.goodsUnitConversionList[0].quantity
          row.allocationUnit = row.goodsUnitConversionList[0].unitCode
          row.allocationUnitName = row.goodsUnitConversionList[0].unitName
        } else {
          row.allocationUnit = ''
          row.allocationUnitName = ''
        }
      },
      // 保存
      funcSubmitSave() {
        this.form.allocationItemList = this.$refs.xTable.tableData;
        const data = this.form;
        if (!this.$refs.xTable.tableData.length) {
          this.$message.error('请新增明细')
        } else {
          this.$refs.form.validate((valid) => {
            if (valid) {
              this.$refs.xTable.validate((valids) => {
                if(valids){
                  this.form.status = 0;
                  this.isDisable = true;
                  allocationAdd(data).then(response => {
                    this.$message({ message: response.msg, type: 'success' })
                    this.$emit('fatherAddMethod');
                    this.isDisable = false;
                  }).then(() => {
                    this.$eventBus.$emit('refreshList')
                    this.$store.dispatch("tagsView/delView", this.$route);
                    this.$router.push({
                      path: "/kngl/allocationList"
                    });
                  }).catch(() => this.isDisable = false)
                }else {
                  return false
                }
              })
            } else {
              return false
            }
          })
        }
      },
      // 提交
      funcSubmitCheck() {
        this.form.allocationItemList = this.$refs.xTable.tableData;
        const data = this.form
        if (!this.$refs.xTable.tableData.length) {
          this.$message.error('请新增明细')
        } else {
          this.$refs['form'].validate((valid) => {
            if (valid) {
              this.$refs.xTable.validate((valids) => {
                if(valids){
                  this.form.status = 1;
                  this.isDisable = true;
                  allocationAdd(data).then(response => {
                    this.$message({ message: response.msg, type: 'success' })
                    this.$emit('fatherAddMethod');
                    this.isDisable = false;
                  }).then(() => {
                    this.$eventBus.$emit('refreshList')
                    this.$store.dispatch("tagsView/delView", this.$route);
                    this.$router.push({
                      path: "/kngl/allocationList"
                    });
                  }).catch(() => this.isDisable = false)
                }else {
                  return false
                }
              })
            } else {
              return false
            }
          })
        }
      },
      footerMethod ({ columns, data }) {
        return [
          columns.map((column, columnIndex) => {
            if (columnIndex === 1) {
              return '合计'
            }
            if (['allocationUnitQuantity'].includes(column.property)) {
                return XEUtils.sum(data, column.property)
            }
            return '-'
          })
        ]
      }
    }
  }
</script>
<style lang="scss" scoped>
  .dialog-footer {
    margin: 75px auto;
    width: 175px;
    // float: right;
  }
</style>

<style>
  .vxe-table .vxe-body--column:not(.col--ellipsis), .vxe-table .vxe-footer--column:not(.col--ellipsis), .vxe-table .vxe-header--column:not(.col--ellipsis) {
    padding: 6px 0;
  }
  .vxe-toolbar{padding:0 0 10px 0}
</style>
